<?php

namespace Sharks\Core\Http;

use Sharks\Core\Support\Bag\ParameterBag;
use Sharks\Core\Support\Base\DesCrypt;

/**
 * Cookie控制。
 * 获取Cookie与设置Cookie
 */
class Cookie {

    private $requestCookie;
    private $responseCookie;
    private $desCrypt;//用于加密cookie值

    public function __construct() {
        $this->requestCookie = new ParameterBag($_COOKIE);
        $this->responseCookie = new ParameterBag();

        $this->desCrypt = new DesCrypt("may-the-");
        $this->desCrypt->setIV("with-you");
    }

    public function has($name) {
        return $this->requestCookie->has($name);
    }

    public function get($name, $default = null) {
        $value = $this->requestCookie->get($name, $default);
        return is_null($value) ? null : $this->desCrypt->decode($value);
    }

    /**
     * @param $name
     * @param $value
     * @param int $expire coookie过期时间，按秒的整数
     * @param null $path
     * @param null $domain
     * @param null $secure
     */
    public function set($name, $value, $expire = 1 * 60 * 60, $path = "/", $domain = null, $secure = null) {
        $this->responseCookie->put($name, array(
            'value'=> is_null($value) ? null : $this->desCrypt->encode($value),
            'expire'=>$expire + time(),
            'path'=>$path,
            'domain'=>$domain,
            'secure'=>$secure
        ));
    }

    /**
     * 所有客户端请求cookie 
     */
    public function requestCookie() {
        return $this->requestCookie->all();
    }

    /**
     * 所有响应cookie
     */
    public function responseCookie() {
        return $this->responseCookie->all();
    }

}